import { WeaTab, WeaLocaleProvider } from 'ecCom';
import React from 'react';
import isMobile from "../../../../utils/mobileDetect";
import './Container.less';
import FormView from './FormView';
import Confirm from "./pane/Confirm";
import Error from "./pane/Error";
import NoRight from './pane/NoRight';
import Success from "./pane/Success";
import { observer } from "mobx-react";
import classNames from 'classnames';
import { viewTypes, resultTypes } from "../../../../constants/form";
import { Icon } from 'antd';
import { Link } from 'react-router';
import getUrlParams from '../../../../utils/getUrlParams';
import ThemeContext from "../theme";

const getLabel = WeaLocaleProvider.getLabel;
const { Provider } = ThemeContext;
const isMobileView = isMobile();
const getTabs = () => [
  {
    title: getLabel(523075, '表单'),
    tabKey: 'form'
  },
  {
    title: getLabel(523076, '收集结果'),
    tabKey: 'statistics'
  }
]

@observer
export default class Container extends React.Component {
  constructor(props) {
    super(props);

    this.store = props.store;
    this.state = {
      tabKey: 'form',
    }
  }

  componentWillMount() {
    const { getSubmitCount } = this.store;

    getSubmitCount();
  }

  onTabKeyChange = tabKey => {
    this.setState({ tabKey });
  }

  getFormContent = (showHeader) => {
    const {
      error,
      noRight,
      success,
      editConfirm,
      successMessage,
      formHeader,
      handleEdit,
      handleNew,
      isShowRepairTitle,
      theme,
      joinCube
    } = this.store;

    if (error && error.api_errormsg) {
      return <Error msg={error.api_errormsg} showHeader={showHeader} />;
    }

    if (noRight) {
      return <NoRight noRight={noRight} showHeader={showHeader} store={this.store} />;
    }

    if (success || editConfirm) {
      const { background } = theme; 
      const isBgImg = 0 == background.type;
      const clsNameStr = classNames('wea-edc-pane-box', {
        'wea-edc-fv-wrapper-mobilebg': isMobileView && isBgImg
      });

      return (
        <div className={clsNameStr}
          style={isMobileView && isBgImg ? {} : background.css}
        >
          {
            success ?
              <Success
                title={formHeader && formHeader.config.title}
                successMessage={successMessage}
                showHeader={showHeader}
                top={isShowRepairTitle ? 40 : 0}
              />
              :
              <Confirm
                title={formHeader && formHeader.config.title}
                handleEdit={handleEdit}
                handleNew={handleNew}
                showHeader={showHeader}
              />
          }
        </div>
      );
    }

    return (
      <Provider value={Object.assign({}, theme, joinCube)}>
        <FormView store={this.store} showHeader={showHeader} />
      </Provider>
    );
  }

  gotoStatistics = () => {
    const { appid } = this.store;

    window.location.href = `/spa/edc/static4mobile/index.html#/form/statistics/${appid}`;
  }

  render() {
    const {
      rightLevel = 0,
      error,
      noRight,
      noEdit,
      appid,
      theme,
      submitCount = '0',
      fillinEnable,
      viewType,
      shortkey,
      isShowRepairList,
      code,
      repairDate,
      toggleRepairList,
      closeRepairTitle,
      isShowRepairTitle,
    } = this.store;
    const { tabKey } = this.state;
    const { background, form } = theme;
    const { statisticsMode, backBtnAble, conversationId = '', conversationType = '', registerSign = '' } = getUrlParams();
    const showTab = Number(statisticsMode) === 1 && rightLevel > 0;
    const showHeader = isMobileView ? true : !showTab;
    const bgColor = (theme && theme.header.type == 0) ? theme.header.css.backgroundColor : '#0270c1';
    const showForm = !isMobileView && !error && !noRight;
    const iframeHeight = document.body.clientHeight - 110;
    const repairCls = classNames('repair-tip', {
      'mobile-timelimit-repair': isMobileView
    });
    const repairPah = `/repair`;//本地开发模式需改成/edc/formview/${shortkey}/repair
    const bgClsNameStr = classNames('wea-edc-fv-wrapper', {
      'mobile-device': isMobileView,
      'wea-edc-fv-wrapper-mobilebg': isMobileView && background.type == 0,
      'wea-edc-fv-wrapper-mobilefull': isMobileView && form.mFullWidth,
      'wea-edc-fv-wrapper-form': showTab && !isMobileView && !isShowRepairList,
      'wea-edc-fv-wrapper-form-mobile': (showTab || noEdit) && isMobileView && !repairDate && !isShowRepairList,
      'wea-edc-fv-wrapper-form-back': backBtnAble === 'true',
      'wea-edc-fv-wrapper-form-edit-again': viewType === viewTypes.READONLY && code === resultTypes.NORMAL,
      'wea-edc-fv-wrapper-form-mobile-edit-again': isMobileView && viewType === viewTypes.READONLY && code === resultTypes.NORMAL,
      'wea-edc-fv-repair': isShowRepairTitle && isMobileView
    });

    return (
      <React.Fragment>
        {backBtnAble === 'true' ?
          <div className='wea-edc-back'>
            <span>
              <i className="icon-coms-Browse-box-delete" onClick={() => {
                window.location.href = `/spa/edc/static4mobile/index.html#/form/statistics/${appid}?backBtnAble=true`;
              }} />
            </span>
          </div> : null
        }
        <div
          className={bgClsNameStr}
          ref={wrapper => this.wrapper = wrapper}
          style={(background.type == 0 && !showForm) && {} || background.css}
        >
          <React.Fragment>
            {
              (showTab && !isMobileView) ?
                <WeaTab
                  datas={getTabs()}
                  keyParam="tabKey"
                  className='wea-edc-view-tab'
                  selectedKey={tabKey}
                  onChange={this.onTabKeyChange}
                  style={{ backgroundColor: bgColor }}
                /> : null
            }
            {(showTab && isMobileView && !repairDate) ?
              <div className='wea-edc-colect-msg' >
                <div onClick={this.gotoStatistics}>
                  <div>
                    <span>{fillinEnable ? getLabel(523077, '收集中') : getLabel(523078, '收集已停止')}，{submitCount}{getLabel(523079, '人已填写')}</span>
                    <i className="icon-coms-Right" />
                  </div>
                </div>
              </div> : null
            }

            {tabKey === 'form' ?
              <React.Fragment>
                {
                  viewType !== viewTypes.READONLY && isShowRepairTitle ?
                    <div className={repairCls}>
                      {
                        repairDate ?
                          <div>
                            <i className="icon-coms02-Warning-01" />
                            <div style={{ flex: '1 1' }}>
                              <span>{getLabel('519970', '您正在补交 #repairdate# 的表单填报数据').replace('#repairdate#', repairDate.replace(', ', ' ~ '))}</span>
                            </div>
                            <Icon type="cross" onClick={closeRepairTitle} />
                          </div>
                          :
                          <div>
                            <div className='header-text'>
                              <span>{`${getLabel('523087', '有逾期未提交的表单')}，`}</span>
                              <Link to={repairPah}>{getLabel('523088', '点击补交')}</Link>
                            </div>
                            <Icon type="cross" onClick={closeRepairTitle} />
                          </div>
                      }
                    </div>
                    : null
                }
                {this.getFormContent(showHeader)}
                {
                  viewType === viewTypes.READONLY && (
                    code === resultTypes.NORMAL
                      ?
                      <div
                        className={classNames('wea-edc-edite-again', { 'wea-edc-edite-again-mobile': isMobileView })}
                        style={{ backgroundColor: bgColor }}
                      >
                        <a href={`/edc/formview/${shortkey}?conversationId=${conversationId}&conversationType=${conversationType}&registerSign=${registerSign}`}>
                          {getLabel(523080, '我要填写')}
                        </a>
                      </div>
                      : (
                        isShowRepairTitle &&
                        <div
                          className={classNames('wea-edc-edite-again', { 'wea-edc-edite-again-mobile': isMobileView })}
                          style={{ backgroundColor: bgColor }}
                          onClick={() => toggleRepairList(true)}
                        >
                          <Link to={repairPah}>{`${getLabel('523087', '有逾期未提交的表单')}，${getLabel('523088', '点击补交')}`}</Link>
                        </div>
                      )
                  )
                }
              </React.Fragment> :
              <div className='wea-edc-statistics'>
                <iframe src={`/spa/edc/static4mobile/index.html#/form/statistics/${appid}`} style={{ height: iframeHeight }} />
              </div>
            }
          </React.Fragment>
        </div>
      </React.Fragment>
    )
  }
}